package com.example.okhttpdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        // 创建OkHttpClient实例
//        val client = OkHttpClient()
//
//        // 创建GET请求
//        val url = "https://jsonplaceholder.typicode.com/posts/1" // 替换为您想要请求的URL
//        val request: Request = Builder()
//            .url(url)
//            .build()
//
//        // 异步执行请求
//        client.newCall(request).enqueue(object : Callback {
//            override fun onFailure(call: Call, e: IOException) {
//                Log.e(TAG, "请求失败: " + e.message)
//            }
//
//            @Throws(IOException::class)
//            override fun onResponse(call: Call, response: Response) {
//                if (response.isSuccessful) {
//                    val responseBody = response.body!!.string()
//                    // 在UI线程中更新UI
//                    runOnUiThread { // 处理响应数据，这里只是简单打印响应内容
//                        Log.d(TAG, "响应内容: $responseBody")
//                    }
//                } else {
//                    Log.e(TAG, "请求失败，错误码: " + response.code)
//                }
//            }
//        })

        // 创建OkHttpClient实例
        val client = OkHttpClient()
        // 创建一个 HTTP 请求
        val url = "https://jsonplaceholder.typicode.com/posts/1"
        val request = Request.Builder()
            .url(url)
            .build()
        val response = client.newCall(request).execute();

        // 发送请求并获取响应
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                println("请求失败: ${response.code}")
                return
            }

            // 从响应中获取响应体数据
            val responseBody = response.body
            val responseBodyString = responseBody?.string()

            println("响应数据:")
            println(responseBodyString)
        }
    }

    companion object {
        private const val TAG = "OkHttpExample"
    }
}